<?php
require_once __DIR__ . '/../../functions.php';

// 检查管理员权限
if (!isAdmin()) {
    die('您没有权限访问此页面');
}

$orderId = intval($_GET['id'] ?? 0);

if ($orderId <= 0) {
    die('订单ID无效');
}

$db = getDB();

// 获取订单信息和用户详细信息
$stmt = $db->prepare("SELECT o.*, u.username, u.phone, u.group_name, u.wechat_account, u.alipay_account, u.wechat_nickname FROM orders o LEFT JOIN users u ON o.user_id = u.id WHERE o.id = ?");
$stmt->execute([$orderId]);
$order = $stmt->fetch();

if (!$order) {
    die('订单不存在');
}

// 获取群组名称标签
$groupNameLabel = getConfigOptionLabel('group_name', $order['group_name']);
?>

<form method="POST" enctype="multipart/form-data" class="needs-validation" novalidate>
    <input type="hidden" name="action" value="update_status">
    <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
    
    <div class="row">
        <div class="col-md-6">
            <h6>订单信息</h6>
            <table class="table table-sm">
                <tr><td><strong>订单ID：</strong></td><td><?php echo $order['id']; ?></td></tr>
                <tr><td><strong>商品名称：</strong></td><td><?php echo htmlspecialchars($order['product_name']); ?></td></tr>
                <tr><td><strong>收货地：</strong></td><td><?php echo htmlspecialchars(getConfigOptionLabel('delivery_location', $order['delivery_location'])); ?></td></tr>
                <tr><td><strong>下单平台：</strong></td><td><?php echo htmlspecialchars(getConfigOptionLabel('order_platform', $order['order_platform'])); ?></td></tr>
                <tr><td><strong>物流单号：</strong></td><td><?php echo htmlspecialchars($order['tracking_no']); ?></td></tr>
                <tr><td><strong>下单金额：</strong></td><td><?php echo formatAmount($order['order_amount']); ?></td></tr>
                <tr><td><strong>付款方式：</strong></td><td><?php echo getPaymentMethodText($order['payment_method']); ?></td></tr>
            </table>
        </div>
        <div class="col-md-6">
            <h6>用户信息</h6>
            <table class="table table-sm">
                <tr><td><strong>用户名：</strong></td><td><?php echo htmlspecialchars($order['username']); ?></td></tr>
                <tr><td><strong>手机号：</strong></td><td><?php echo htmlspecialchars($order['phone']); ?></td></tr>
                <tr><td><strong>群组：</strong></td><td><?php echo htmlspecialchars($groupNameLabel); ?></td></tr>
                <?php if ($order['wechat_account']): ?>
                    <tr><td><strong>微信账号：</strong></td><td><?php echo htmlspecialchars($order['wechat_account']); ?></td></tr>
                <?php endif; ?>
                <?php if ($order['wechat_nickname']): ?>
                    <tr><td><strong>微信昵称：</strong></td><td><?php echo htmlspecialchars($order['wechat_nickname']); ?></td></tr>
                <?php endif; ?>
                <?php if ($order['alipay_account']): ?>
                    <tr><td><strong>支付宝账号：</strong></td><td><?php echo htmlspecialchars($order['alipay_account']); ?></td></tr>
                <?php endif; ?>
            </table>
            
            <h6>当前状态</h6>
            <div class="mb-3">
                <span class="badge bg-<?php echo getOrderStatusClass($order['status']); ?> fs-6">
                    <?php echo getOrderStatusText($order['status']); ?>
                </span>
            </div>
            
            <?php if ($order['status'] == 'settled' && $order['settlement_amount']): ?>
                <div class="mb-3">
                    <strong>结算金额：</strong>
                    <span class="text-success"><?php echo formatAmount($order['settlement_amount']); ?></span>
                </div>
            <?php endif; ?>
            
            <?php if ($order['settlement_info']): ?>
                <div class="mb-3">
                    <strong>结算信息：</strong>
                    <p class="text-muted small"><?php echo nl2br(htmlspecialchars($order['settlement_info'])); ?></p>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <?php if ($order['order_screenshot']): ?>
        <div class="mb-4">
            <h6>订单截图</h6>
            <img src="<?php echo UPLOAD_URL . 'orders/' . $order['order_screenshot']; ?>" 
                 class="img-fluid rounded border" style="max-height: 200px;">
        </div>
    <?php endif; ?>
    
    <?php if ($order['settlement_screenshot']): ?>
        <div class="mb-4">
            <h6>结算截图</h6>
            <img src="<?php echo UPLOAD_URL . 'settlements/' . $order['settlement_screenshot']; ?>" 
                 class="img-fluid rounded border" style="max-height: 200px;">
        </div>
    <?php endif; ?>
    
    <hr>
    
    <div class="row">
        <div class="col-md-6">
            <div class="mb-3">
                <label for="status" class="form-label">更改状态 <span class="text-danger">*</span></label>
                <select class="form-select" id="status" name="status" required>
                    <option value="pending" <?php echo $order['status'] == 'pending' ? 'selected' : ''; ?>>未结算</option>
                    <option value="settled" <?php echo $order['status'] == 'settled' ? 'selected' : ''; ?>>已结算</option>
                    <option value="refunded" <?php echo $order['status'] == 'refunded' ? 'selected' : ''; ?>>已退还</option>
                </select>
            </div>
            
            <div class="mb-3" id="settlementFields">
                <div class="mb-3">
                    <label for="settlement_type" class="form-label">结算类型 <span class="text-danger">*</span></label>
                    <select class="form-select" id="settlement_type" name="settlement_type" required>
                        <option value="commission" <?php echo ($order['settlement_type'] ?? 'commission') == 'commission' ? 'selected' : ''; ?>>结本金</option>
                        <option value="principal_commission" <?php echo ($order['settlement_type'] ?? '') == 'principal_commission' ? 'selected' : ''; ?>>结本金+佣金</option>
                    </select>
                </div>
                
                <div class="mb-3">
                    <label for="settlement_amount" class="form-label">结算金额</label>
                    <input type="number" class="form-control" id="settlement_amount" name="settlement_amount" 
                           step="0.01" min="0" value="<?php echo $order['settlement_amount'] ?? $order['order_amount']; ?>" 
                           placeholder="留空则根据结算类型自动计算">
                    <div class="form-text">如果留空，将根据结算类型自动计算金额</div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="mb-3">
                <label for="settlement_info" class="form-label">结算信息</label>
                <textarea class="form-control" id="settlement_info" name="settlement_info" 
                          rows="4" placeholder="请输入结算说明、备注等"><?php echo htmlspecialchars($order['settlement_info'] ?? ''); ?></textarea>
            </div>
            
            <!-- 在结算截图上传部分添加当前截图显示 -->
            <div class="mb-3">
                <label for="settlement_screenshots" class="form-label">结算截图</label>
                <input type="file" class="form-control" id="settlement_screenshots" name="settlement_screenshots[]" 
                       accept="image/*" multiple>
                <div class="form-text">支持多张图片，格式：JPG、PNG、GIF，最大 5MB/张</div>
                
                <!-- 图片预览区域 -->
                <div id="imagePreview" class="mt-2"></div>
                
                <!-- 当前结算截图显示 -->
                <?php
                // 获取当前订单的结算截图（从操作记录中获取最新的）
                $currentSettlementScreenshots = [];
                if (!empty($operations)) {
                    foreach ($operations as $op) {
                        if ($op['screenshots']) {
                            $screenshots = json_decode($op['screenshots'], true);
                            if (is_array($screenshots) && !empty($screenshots)) {
                                foreach ($screenshots as $screenshot) {
                                    if (!empty($screenshot) && !in_array($screenshot, $currentSettlementScreenshots)) {
                                        $currentSettlementScreenshots[] = $screenshot;
                                    }
                                }
                            }
                        }
                    }
                }
                ?>
                
                <?php if (!empty($currentSettlementScreenshots)): ?>
                    <div class="mt-3">
                        <label class="form-label">当前结算截图</label>
                        <div class="row">
                            <?php foreach ($currentSettlementScreenshots as $screenshot): ?>
                                <div class="col-md-3 mb-3">
                                    <div class="card">
                                        <a href="<?php echo UPLOAD_URL . 'settlements/' . $screenshot; ?>" target="_blank">
                                            <img src="<?php echo UPLOAD_URL . 'settlements/' . $screenshot; ?>" class="card-img-top" style="height: 120px; object-fit: cover;">
                                        </a>
                                        <div class="card-body p-2">
                                            <button type="button" class="btn btn-sm btn-outline-danger w-100" onclick="deleteOrderSettlementScreenshot(<?php echo $order['id']; ?>, '<?php echo $screenshot; ?>')">
                                                <i class="bi bi-trash"></i> 删除
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
            </div>
        </div>
    </div>
    
    <div class="alert alert-info">
        <i class="bi bi-info-circle"></i>
        <strong>说明：</strong>将订单状态改为"已结算"会将此订单汇总到用户的待结账单中，在结算管理页面进行实际打款操作。
    </div>
    
    <div class="text-end">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="submit" class="btn btn-primary">
            <i class="bi bi-save"></i> 保存更改
        </button>
    </div>
</form>

<script>

// 删除订单结算截图
function deleteOrderSettlementScreenshot(orderId, filename) {
    if (!confirm('确定要删除这张结算截图吗？')) {
        return;
    }
    
    fetch('../admin/api/delete_order_settlement_screenshot.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            order_id: orderId,
            filename: filename
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('截图删除成功', 'success');
            // 重新加载表单
            editOrder(orderId);
        } else {
            showToast('删除失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showToast('删除失败: ' + error.message, 'danger');
    });
}
// 显示/隐藏结算相关字段
function toggleSettlementFields() {
    const statusSelect = document.getElementById('status');
    const settlementFields = document.getElementById('settlementFields');
    
    if (statusSelect.value === 'settled') {
        settlementFields.style.display = 'block';
    } else {
        settlementFields.style.display = 'none';
    }
}

// 初始化
document.getElementById('status').addEventListener('change', toggleSettlementFields);
toggleSettlementFields(); // 初始状态

// 表单验证
(function() {
    'use strict';
    window.addEventListener('load', function() {
        const forms = document.querySelectorAll('.needs-validation');
        Array.prototype.filter.call(forms, function(form) {
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();
</script>